<template>
  <div class="carpay-container">
    <div class="search-container">
      <span class="search-label">企业名称：</span>
      <el-input
        v-model.trim="searchs.enterpriseName"
        clearable
        placeholder="请输入企业名称"
        class="search-main"
      />

      <span class="search-label">缴费时间：</span>
      <el-date-picker
        v-model="value1"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button type="primary" class="search-btn" @click="doSearch"
        >查询</el-button
      >
    </div>
    <el-button type="primary" class="search-btn one" @click="add"
      >添加账单</el-button
    >

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="序号" width="60">
        <template slot-scope="scope">
          {{ 10 * (params.page - 1) + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="billNumber" label="账单编号" width="180">
      </el-table-column>
      <el-table-column prop="enterpriseName" label="企业名称" width="280">
      </el-table-column>
      <el-table-column prop="buildingName" label="租赁楼宇"> </el-table-column>
      <el-table-column prop="propertyFeePrice" label="物业费（元/m²）">
      </el-table-column>
      <el-table-column prop="paymentAmount" label="账单金额（元）">
      </el-table-column>
      <el-table-column prop="createTime" label="缴费时间"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" type="text" @click="dialog(scope.row.id)"
            >查看</el-button
          >
          <el-button size="mini" type="text" @click="delRent(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="pageChange"
      :current-page="params.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="params.pageSize"
      layout="total,  prev, pager, next, sizes, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- tanchuang -->
    <el-dialog
      title="添加账单"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="选择租户"
          :label-width="formLabelWidth"
          prop="enterpriseId"
        >
          <el-select v-model="form.enterpriseId" placeholder="请选择租户">
            <el-option
              v-for="item in enterpriseList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="租赁楼宇"
          :label-width="formLabelWidth"
          prop="buildingId"
        >
          <el-select v-model="form.buildingId" placeholder="请选择租赁楼宇">
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="缴费周期"
          :label-width="formLabelWidth"
          prop="time"
        >
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="支付金额"
          :label-width="formLabelWidth"
          prop="paymentAmount"
        >
          <el-input
            v-model="price"
            autocomplete="off"
            placeholder="请输入支付金额"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="支付方式"
          :label-width="formLabelWidth"
          prop="paymentMethod"
        >
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option
              v-for="item in payLsit"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- two -->
    <el-dialog
      class="two"
      title="查看账单"
      :visible.sync="dialogVisibleTwo"
      width="30%"
      :before-close="handleClose"
    >
      <el-row
        class="dialog-content"
        v-for="(item, index) in dialogData"
        :key="index"
      >
        <el-col :span="10">
          <span class="label-text">{{ item.label }}:</span>
        </el-col>
        <el-col :span="14">
          <span class="value-text">{{ item.value }}</span>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleTwo = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleTwo = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPropetyList,
  getPropetyEnterpriseAPI,
  getPropetyBuildingAPI,
  addPropetyAPI,
  getPropertyfee,
  delPropertyfee
} from "@/api/propety";
import { Message } from "element-ui";
export default {
  data() {
    return {
      dialogVisibleTwo: false,
      dataList: {},
      payLsit: [
        { id: 1, name: "微信" },
        { id: 2, name: "支付宝" },
        { id: 3, name: "现金" },
      ],
      enterpriseList: [],
      buildingList: [],
      form: {
        enterpriseId: "",
        buildingId: "",
        time: "",
        paymentAmount: "",
        paymentMethod: "",
      },
      rules: {
        enterpriseId: [
          { required: true, message: "请选择租户", trigger: "blur" },
        ],
        buildingId: [
          { required: true, message: "请选择租赁楼宇", trigger: "blur" },
        ],
        time: [{ required: true, message: "请输入缴费周期", trigger: "blur" }],
        paymentAmount: [
          { required: false, message: "请输入物业费", trigger: "blur" },
        ],
        paymentMethod: [
          { required: true, message: "请选择支付方式", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      value1: [],
      searchs: {
        enterpriseName: null,
      },
      tableData: [],
      total: 0,
      params: {
        page: "1",
        pageSize: "10",
        enterpriseName: "",
        start: "",
        end: "",
      },
    };
  },
  computed: {
    dialogData: {
      get() {
        if (this.dataList) {
          return [
            { label: "租户名称", value: this.dataList.enterpriseName },
            { label: "租赁楼宇", value: this.dataList.buildingName },
            { label: "缴费周期",value: `${this.dataList.startTime}至${this.dataList.endTime}`},
            { label: "物业费（元/m²）", value: this.dataList.propertyFeePrice },
            { label: "账单金额（元）", value: this.dataList.paymentAmount },
            { label: "支付方式", value: this.dataList.paymentMethodValue },
            { label: "缴费时间", value: this.dataList.createTime },
          ];
        }
      },
    },
    price: {
      get() {
        if (this.form.time[0] && this.form.time[1]) {
          const calculateDaysDifference = (dateStr1, dateStr2) => {
            let dateObj1 = new Date(dateStr1);
            let dateObj2 = new Date(dateStr2);
            let timeDiff = Math.abs(dateObj1.getTime() - dateObj2.getTime());
            let daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
            return daysDiff;
          };
          const res = calculateDaysDifference(
            this.form.time[0],
            this.form.time[1]
          );
          return res * 41.67;
        }
        return "请输入支付金额"; // 当条件不满足时，返回默认值 0
      },
    },
  },
  created() {
    this.render(this.params);
  },
  methods: {
    async delRent(id){
      try{
        await this.$confirm('确认删除？')
        await delPropertyfee(id)
        Message.success('删除成功')
        this.render(this.params);
      }catch(err){
Message.error('删除失败，请重试')
      }
    },
    async dialog(id) {
      const { data } = await getPropertyfee(id);
      this.dataList = data;
      this.dialogVisibleTwo = true;
    },
    async confirmSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        if (this.price) {
          let data = {
            enterpriseId: this.form.enterpriseId,
            buildingId: this.form.buildingId,
            paymentAmount: this.price,
            paymentMethod: this.form.paymentMethod,
            startTime: this.formatDate(this.form.time[0]),
            endTime: this.formatDate(this.form.time[1]),
          };
          await addPropetyAPI(data);
          Message.success("添加成功");
          this.dialogVisible = false;
          this.$refs.form.resetFields();
          this.render(this.params);
        }
      });
    },
    add() {
      this.getName();
      this.dialogVisible = true;
    },
    async getName() {
      let { data } = await getPropetyEnterpriseAPI();
      this.enterpriseList = data;
      let res = await getPropetyBuildingAPI();
      this.buildingList = res.data;
    },
    formatDate(dateStr) {
      let dateObj = new Date(dateStr);
      let year = dateObj.getFullYear();
      let month = (dateObj.getMonth() + 1).toString().padStart(2, "0");
      let day = dateObj.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    doSearch() {
      this.params.enterpriseName = this.searchs.enterpriseName;
      this.params.start = this.formatDate(this.value1[0]);
      this.params.end = this.formatDate(this.value1[1]);
      console.log(this.params);

      this.render(this.params);
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.render(this.params);
    },
    pageChange(page) {
      this.params.page = page;
      this.render(this.params);
    },
    async render(params) {
      try {
        const { data } = await getPropetyList(params);
        this.total = data.total;
        this.tableData = data.rows;
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .two .el-dialog,::v-deep .two .el-dialog__footer {
  border-radius: 20px; 
}
::v-deep .two .dialog-footer{
  display: block;
  height: 100%;
  .el-button{
    margin-top: 20px;
    margin-right: 20px;
  }
}

::v-deep .two .el-dialog__footer{
  background-color: #f4f6f8;
  padding: 0;
}
::v-deep .dialog-content.el-row .el-col-10{
  text-align: right;
  color:gray,
}
::v-deep .dialog-content.el-row .el-col-14{
  text-indent: 1em;
}
::v-deep .dialog-content.el-row{
  margin: 20px;
  font-size: 20px;
}

::v-deep .el-form .el-date-editor {
  width: 100%;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-button.el-button--primary {
  margin-bottom: 20px;
}
::v-deep .el-table__header-wrapper th {
  background-color: #f4f6f8;
}
::v-deep .el-pagination {
  margin-top: 30px;
  text-align: right;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-main {
    width: 200px;
    margin-right: 10px;
  }
  .search-btn {
    margin-left: 20px;
    margin-top: 20px;
  }
}
.search-btn.one {
  margin-top: 20px;
}
::v-deep .el-range-separator {
  display: inline-block;
  width: 30px;
}
</style>



